import {app} from "@/main"

/**
 * 判断buttonKey是否存在
 * @param buttons
 * @param type
 * @param value
 */
const isExit = (buttons,type,value) => {
    for (let item of buttons){
        // console.log(`item.permissionId: ${item.permissionId}/value${(value!==undefined?value+'':'')}`)
        if(type==='buttonKey' && item.permissionId === (value!==undefined?value+'':'')){
            return item;
        }
        if(type==='buttonValue' && item.name === value){
            return item;
        }
    }
}

/**
 * 检查buttonKey是否存在
 * @param el
 * @param routerValue
 * @param buttonKey
 */
const checkKey = (el,routerValue,buttonKey) => {
    let buttons = routerValue.meta.buttons;
    if(buttonKey===''){
        let text = el.innerText;
        return  isExit(buttons,'buttonValue',text)!==undefined;
    }
    if(buttonKey!==''){
        return  isExit(buttons,'buttonKey',buttonKey)!==undefined;
    }
    return false;
}

const permission = {
    mounted(el, binding) {
        const { value } = binding;
        let routerValue = app.config.globalProperties.$router.currentRoute.value;
        let key = checkKey(el,routerValue,value || '');
        if(!key){//没有权限
            el.remove()  //删除按钮
        }
    }
};

export default permission;